//
//  NetworkTools.swift
//  YeKa
//
//  Created by Gina on 15/10/14.
//  Copyright © 2015年 Gina. All rights reserved.
//

import UIKit
import AFNetworking




private let YeKaErrorDomainName = "yeka.error"

/// 网络访问方法
enum YeKaNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    
    
    // 网络工具单例
    static let sharedNetworkTools: NetworkTools = {
        let instance = NetworkTools(baseURL: NSURL(string: "http://app.ycombo.com/"))
        
        // 设置数据解析数据类型
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return instance
    }()
    
    // MARK:    封装AFN网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    
    // 定义一个类型别名
    typealias YeKaNetFinishedCallBack = (result: [String: AnyObject]?, error:NSError?) -> ()
    
    /*
    AFN 网络请求 GET / POST
    参数：HTTP 方法 GET / POST、地址、参数字段、完成回调。
    */
    func request(method: YeKaNetworkMethod, urlString: String, params: [String: AnyObject]?, finished: YeKaNetFinishedCallBack) {
        
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                finished(result: nil, error: nil)
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            finished(result: nil, error: error)
        }
        
        // 3. 根据 method 来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
        
        
    }
    
}
